<script setup>
import {useRouter} from "vue-router";
import {onBeforeUnmount, onMounted, ref} from "vue";
import axios from "axios";
import flvjs from "flv.js";
import {showToast} from "vant";

const router = useRouter();

const cameraId = ref("");
const videoUrl = ref("");
const player = ref(null);

const webrtcServer = ref(null);
const flvplayer = ref(null);
const playerWidth = ref(0);
const playerHeight = ref(0);
const info = ref("");
const isFullScreen = ref(false);

const getPlayUrl = (cameraId) => {
  axios.get("/api/getstreamurl/" + cameraId )
      .then(res => {
        console.log(res.data)
        if(res.data.hasOwnProperty("code") && res.data.code == 0){
          // videoUrl.value = encodeURIComponent(res.data.data.url);
          videoUrl.value = res.data.data.url;
          console.log(res.data.data.url)

          //h5player.js
          createPlayer();
          realPlay(videoUrl.value, 0);
          player.value.JS_GetVideoInfo(0)
              .then((res)=>{
                console.log(res);
              });
        }
      })
      .catch(err => {
        console.log(err);
      })
      .finally(() => {

      })
}

//Hik H5Player.js
const createPlayer = () => {
  player.value = new window.JSPlugin({
    szId: "player",
    szBasePath: "js/h5player",
    iMaxSplit: 1,
    openDebug: true,
    oStyle:{
      beforeSelect: "#409EFF"
    }
  })

  player.value.JS_SetWindowControlCallback(
      {
        windowEventSelect: function (index) { //插件选中窗口回调
          console.log("window select callback:"+index);
        },
        pluginErrorHandler: function (index, iErrorCode, oError) { //插件错误回调
          // do you want...
          // 取流失败，流中断等错误都会触发该回调函数，请自行对照错误码表进行判断。
          // 业务上层可在此做一些个性化操作，如：个性化错误信息展示，重新取流等。
          console.log("window error callback:"+index+","+iErrorCode+","+oError)
        },
        windowEventOver: function (index) { //鼠标移过回调
          // do you want...
          console.log("window over callback:"+index)
        },
        windowEventOut: function (index) { //鼠标移出回调
          // do you want...
          console.log("window out callback:"+index)
        },
        windowEventUp: function (index) { //鼠标mouseup事件回调
          // do you want...
          console.log("window up callback:"+index)
        },
        windowFullCcreenChange: function (bFull) { //全屏切换回调
          // do you want...
          console.log("window fullscreen change callback:"+bFull)
        },
        firstFrameDisplay: function (index, iWidth, iHeight) { //首帧显示回调
          // do you want...
          playerWidth.value = iWidth;
          playerHeight.value = iHeight;
          resizePlayer();
          console.log("window first frame display callback:"+index+","+iWidth+","+iHeight)
        },
        performanceLack: function () { //性能不足回调
          // do you want...
          console.log("window performance lack callback")
        },
        StreamEnd: function (index) { //回放结束回调,返回对应测窗口id
          // do you want...
          console.log("window stream end callback:"+index)
        }
      });
  // player.value.JS_Resize(360,260).then(()=>{
  //       console.log("resize success")
  //     },
  //     (err)=>{
  //       console.log(err);}
  // )
};

const resizePlayer = ()=>{
  showToast("screen:" + screen.orientation.angle);
  if(screen.orientation.angle == 90 || screen.orientation.angle == 270)
  {
    enterFullScreen(document.getElementById("player"));
  }
  else{
    document.exitFullscreen();
  }
  let width = window.innerWidth;
  let height = window.innerHeight;
  if(playerWidth.value == width)
  {
    return;
  }
  if(width/height<playerWidth.value/playerHeight.value)
  {

    playerHeight.value = width/playerWidth.value*playerHeight.value;
    playerWidth.value = width;
    player.value.JS_Resize(playerWidth.value,playerHeight.value).then(()=>{
      console.log("resize success");
    })
  }
  else{
    playerWidth.value = height/playerHeight.value*playerWidth.value;
    playerHeight.value = height;
    player.value.JS_Resize(playerWidth.value,playerHeight.value).then(()=>{
      console.log("resize success");
    })
  }
  info.value="resized";
}

const realPlay = (url, index)=>{
  let playURL = url;
  let modeDefault = 0;
  console.log(url);
  player.value.JS_Play(url, {playURL,mode:0},0)
      .then(
          ()=>{
            console.log("player success")
          },
          e=>{
            console.log("error",e);
          }
      )
}

const stopPlay = ()=>{
  player.value.JS_StopRealPlayAll().then(
      ()=>{
        console.log("stop player");
      },
      err => {
        console.log("error",err)
      }
  )
}

const fullScreen = (type)=>{
  player.value.JS_FullScreenDisplay(type).then(
      ()=>{
        console.log("FullScreen Success")
      },
      err=>{
        console.log("FullScreen Error:",err)
      }
  )
}

const onOrientationChange = () => {
  if(window.innerWidth >= window.innerHeight)
  {
    isFullScreen.value = true;
  }
  else {
    isFullScreen.value = false;
  }
  resizePlayer();
}

const enterFullScreen = () => {
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.mozRequestFullScreen) { /* Firefox */
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
      element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) { /* IE/Edge */
      element.msRequestFullscreen();
    } else {
      console.log("全屏模式不被支持！");
    }
};

const toggleFullScreen = () => {
  const element = document.documentElement;
  if (!isFullScreen) {
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.mozRequestFullScreen) { /* Firefox */
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
      element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) { /* IE/Edge */
      element.msRequestFullscreen();
    }

    // 隐藏浏览器的某些元素
    hideElements();
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) { /* Firefox */
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */
      document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) { /* IE/Edge */
      document.msExitFullscreen();
    }

    // 显示隐藏的元素
    showElements();
  }
};

const hideElements = () => {
  // 这里可以添加需要隐藏的元素
  const titleBar = document.querySelector('#title-bar');
  if (titleBar) {
    titleBar.style.display = 'none';
  }
};

const showElements = () => {
  // 这里可以添加需要显示的元素
  const titleBar = document.querySelector('#title-bar');
  if (titleBar) {
    titleBar.style.display = 'block';
  }
};

const onFullScreenChange = () => {
  isFullScreen.value = !isFullScreen.value;
  // resizePlayer();
};


onMounted(() => {
  console.log(router.currentRoute.value)
  window.addEventListener("resize",resizePlayer);
  cameraId.value = router.currentRoute.value.query.cameraId;
  getPlayUrl(cameraId.value);
  window.addEventListener('orientationchange',resizePlayer);

  // document.addEventListener('fullscreenchange', onFullScreenChange);
  // document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  // document.addEventListener('mozfullscreenchange', onFullScreenChange);
  // document.addEventListener('MSFullscreenChange', onFullScreenChange);
})

onBeforeUnmount(() => {
  stopPlay();
  window.removeEventListener("resize",resizePlayer);
  window.removeEventListener('orientationchange',resizePlayer);

  // document.removeEventListener('fullscreenchange', onFullScreenChange);
  // document.removeEventListener('webkitfullscreenchange', onFullScreenChange);
  // document.removeEventListener('mozfullscreenchange', onFullScreenChange);
  // document.removeEventListener('MSFullscreenChange', onFullScreenChange);
})

</script>

<template>


    <div id="player" :style="{width:playerWidth+'px',height:playerHeight+'px'}"></div>

  <!--  {{cameraId}}-->
<!--  <video-->
<!--      id="video-player"-->
<!--      controls-->
<!--      autoplay-->
<!--      width="100%"-->
<!--  >-->
<!--  </video>-->
  <!--  <video id="flv-player" controls autoplay width="600" height="400">-->

  <!--  </video>-->
<!--  <p>{{videoUrl}}</p>-->

</template>

<style scoped>
#player1 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.container {
  position: relative;;
  height: 100%;
  width: 100%;
}
</style>